﻿// Copyright (c) MichaConrad. All rights reserved. See License.txt in the project root for license information.

namespace LinqToLdapExtensions.Scope
{
    using System.Collections.Generic;
    using LinqToLdap;
    using System;
    using LinqToLdapExtensions.Properties;

    /// <summary>
    /// Provides the ability to call <see cref="IDirectoryContextFactory.GetCurrentContext()"/>
    /// for each System.Web.HttpContext. Works only with web applications.
    /// Supports multiple instances of <see cref="IDirectoryContextFactory"/> in one one HttpContext.
    /// </summary>
    public class WebDirectoryContext : CurrentDirectoryContext
    {
        /// <summary>
        /// The context key.
        /// </summary>
        private const string ContextKey = "LinqToLdapExtensions.Scope.HttpContext.Store";

        /// <summary>
        /// Initializes a new instance of the <see cref="WebDirectoryContext"/> class.
        /// </summary>
        /// <param name="directoryContextFactory">
        /// The directory context factory.
        /// </param>
        public WebDirectoryContext(IDirectoryContextFactory directoryContextFactory)
            : base(directoryContextFactory)
        {
        }

        /// <summary>
        /// Gets the store.
        /// </summary>
        protected override IDictionary<IDirectoryContextFactory, IDirectoryContext> Store
        {
            get
            {
                var context = System.Web.HttpContext.Current;
                if (context == null)
                {
                    throw new InvalidOperationException(Resources.NotInWebContext);
                }

                var dic = context.Items[ContextKey] as IDictionary<IDirectoryContextFactory, IDirectoryContext>;
                if (dic != null)
                {
                    return dic;
                }

                dic = new Dictionary<IDirectoryContextFactory, IDirectoryContext>();
                context.Items[ContextKey] = dic;
                return dic;
            }
        }
    }
}
